﻿namespace MVCResourceEngine
{
    using System;
    using System.Globalization;
    using System.Text;
    using System.Web.Mvc;

    /// <summary>
    /// Provides extension methods for the UrlHelper class
    /// </summary>
    public static class UrlHelperExtensions
    {
        /// <summary>
        /// Returns the path of the resource.
        /// </summary>
        /// <param name="urlHelper">The URL helper.</param>
        /// <param name="resourceName">Name of the resource.</param>
        /// <returns>The path of the resource</returns>
        public static string Resource(this UrlHelper urlHelper, string resourceName)
        {
            // get the resource engine result from the resource engine collection
            var resourceEngineResult = ResourceEngines.Engines.FindResource(urlHelper.RequestContext, resourceName);

            // return the absolute path of the resource if it is not null
            if (resourceEngineResult.Resource != null)
            {
                return urlHelper.Content(resourceEngineResult.Resource);
            }

            // instanciate string builder
            var stringBuilder = new StringBuilder();

            // append all searched locations to the string builder
            foreach (var s in resourceEngineResult.SearchedLocations)
            {
                stringBuilder.Append("\n" + s);
            }

            // throw invalid operation exception listing searched locations
            throw new InvalidOperationException(
                string.Format(
                    CultureInfo.CurrentUICulture,
                    "The resource '{0}' was not found. The following locations were searched:{1}",
                    new object[] { resourceName, stringBuilder }));
        }
    }
}
